package com.authine.cloudpivot.web.api.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.IMMessageFacade;
import com.authine.cloudpivot.engine.api.model.PageableSupport;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizSchemaModel;
import com.authine.cloudpivot.engine.api.model.im.MessageHistoryModel;
import com.authine.cloudpivot.engine.api.model.im.MessageModel;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.api.model.workflow.WorkflowTemplateHeaderModel;
import com.authine.cloudpivot.engine.api.spec.WorkItemQuerySpec;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.status.WorkItemStatus;
import com.authine.cloudpivot.engine.enums.status.WorkflowInstanceStatus;
import com.authine.cloudpivot.engine.enums.type.*;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.service.StoreService;
import com.authine.cloudpivot.web.api.service.TransferService;
import com.authine.cloudpivot.web.api.util.ClientUtils;
import com.authine.cloudpivot.web.api.view.PageVO;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.runtime.TransferResultVO;
import com.authine.cloudpivot.web.api.view.runtime.TransferVO;
import com.authine.cloudpivot.web.api.view.runtime.WorkItemVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.stream.Collectors;

@Api(description = "外企德科相关接口", tags = "工作交接")
@RestController
@RequestMapping("/api/transfer")
@Slf4j
@Validated
public class TransferController extends BaseController {

    @Autowired
    public TransferService transferService;
    @Autowired
    public IMMessageFacade imMessageFacade;

    private volatile boolean isProc = false;
    private final ScheduledExecutorService logExecutorService = new ScheduledThreadPoolExecutor(1, (new BasicThreadFactory.Builder()).namingPattern("log-service-schedule-pool-%d").daemon(true).build());

    @Autowired
    public HttpServletRequest request;


    /**
     * @Description : 获取需要更换的数据
     * @param ： projectId
     * @param ： subjectPersonOld
     * @param ： subjectPersonNew
     * @author : Liun
     * @date : 2020/7/13
     */
    @GetMapping({"/transfer"})
    @ApiOperation(
            value = "更换项目经理",
            notes = "更换项目经理"
    )
    public ResponseResult transfer(String projectId,String userId,String transferUserId,String transferDeptId){
        ResponseResult responseResult=this.getOkResponseResult((Object)null, "工作交接已在运行");
        //查询当前项目经理存在的待办流程数据
        List<WorkItemModel> workItemVOList= this.listUserWorkItems(userId,"","",null, null);

        List<TransferVO> transferVOS=transferService.selectTransferVO(projectId,userId,transferUserId,transferDeptId,workItemVOList);
        //正式交接
        for(TransferVO transferVO:transferVOS){
            responseResult= this.transferWorkItems(transferVO);
        }

        return responseResult;
    }


    /**
     * @Description : 真正数据交接
     * @param ： transferVO
     * @author : Liun
     * @date : 2020/7/13
     */
    public ResponseResult transferWorkItems(TransferVO transferVO) {
        this.checkUser(transferVO.getUserId());
        this.checkUser(transferVO.getTransferUserId());
        if (transferVO.getUserId().equals(transferVO.getTransferUserId())) {
            return this.getErrResponseResult(ErrCode.WORKFLOW_CANNOT_FORWARD_ONESELF.getErrCode(), ErrCode.WORKFLOW_CANNOT_FORWARD_ONESELF.getErrMsg());
        } else {
            TransferResultVO transferResult = new TransferResultVO();
            transferVO.setOriginator(this.getUserId());
            Integer success = 0;
            Integer fails = 0;
            transferResult.setSuccess(success);
            transferResult.setFails(fails);
            if (transferVO.getIsBusiness() != null && transferVO.getIsBusiness()) {
                if (transferVO.getTransferAll() != null && transferVO.getTransferAll() && StringUtils.isEmpty(transferVO.getSchemaCode())) {
                    if (this.isProc) {
                        return this.getErrResponseResult(ErrCode.SYS_BUSINESS_DOING_ERROR.getErrCode(), ErrCode.SYS_BUSINESS_DOING_ERROR.getErrMsg());
                    } else {
                        this.isProc = Boolean.TRUE;
                        (new Thread(() -> {
                            try {
                                this.transferBussiness(transferVO, transferResult);
                                log.info("全量工作交接完成,结果为{}", transferResult);
                                this.sendDingMessage(transferVO, transferResult);
                            } finally {
                                this.isProc = Boolean.FALSE;
                            }

                        })).start();
                        return this.getOkResponseResult((Object)null, "工作交接已在运行");
                    }
                } else {
                    this.transferBussiness(transferVO, transferResult);
                    this.sendDingMessage(transferVO, transferResult);
                    return this.getOkResponseResult(transferResult, "工作交接已选任务或全部任务");
                }
            } else {
                String comment = "这是一条工作交接待办任务.";
                List<WorkItemVO> workItems = Lists.newArrayList();
                if (transferVO.getTransferAll()) {
                    Integer size = 2147483647;
                    PageableSupport pageable = new PageableSupport(0, size, null);
                    WorkItemQuerySpec workItemQuerySpec = new WorkItemQuerySpec();
                    workItemQuerySpec.setUserId(transferVO.getUserId());
                    workItemQuerySpec.setUnitType(UnitType.USER);
                    workItemQuerySpec.setWorkflowCode(transferVO.getWorkflowCode());
                    workItemQuerySpec.setWorkflowName(StringUtils.EMPTY);
                    workItemQuerySpec.setOriginator(transferVO.getOriginator());

                    Page<WorkItemModel> workItemsPage = this.getWorkflowInstanceFacade().queryWorkItems(workItemQuerySpec, pageable);
                    if (log.isDebugEnabled()) {
                        log.debug("结束查询全部待办，开始进行交接...size = {}, workItemsTotalPageSize = {}", size, workItemsPage.getTotalPages());
                    }

                    List<WorkItemModel> workItemModels = workItemsPage.getContent();
                    if (CollectionUtils.isEmpty(workItemModels)) {
                        throw new PortalException(ErrCode.WORKFLOW_WORK_ITEM_EMPTY);
                    }

                    Iterator var11 = workItemModels.iterator();

                    while(var11.hasNext()) {
                        WorkItemModel model = (WorkItemModel)var11.next();

                        WorkItemVO workItemVO;
                        try {
                            Boolean forwardResult = this.forwardWordItemWithNoMessage(transferVO.getUserId(), model.getId(), transferVO.getTransferUserId(), transferVO.getTransferDeptId(), comment);
                            if (log.isDebugEnabled()) {
                                log.debug("全部交接, forwardResult = {}, success = {}, fails = {}", new Object[]{forwardResult, success, fails});
                            }

                            if (forwardResult) {
                                transferResult.setSuccess(transferResult.getSuccess() + 1);
                                this.writeOperationLog(model.getInstanceId(), model.getId(), model.getActivityCode(), OperationType.WORK_ITEM_HANDOVER, transferVO);
                            } else {
                                transferResult.setFails(transferResult.getFails() + 1);
                                workItemVO = new WorkItemVO((WorkItemModel)null);
                                BeanUtils.copyProperties(model, workItemVO);
                                workItems.add(workItemVO);
                            }
                        } catch (Exception var15) {
                            log.error("userId = {}, id = {}, transferUserId = {}", new Object[]{transferVO.getUserId(), model.getId(), transferVO.getTransferUserId()});
                            log.error("交接全部工作时异常，e = {}", var15);
                            transferResult.setFails(transferResult.getFails() + 1);
                            workItemVO = new WorkItemVO((WorkItemModel)null);
                            BeanUtils.copyProperties(model, workItemVO);
                            workItems.add(workItemVO);
                        }
                    }
                } else {
                    if (CollectionUtils.isEmpty(transferVO.getWorkItemIds())) {
                        throw new PortalException(ErrCode.FORWARD_WORKITEM_ID_EMPTY);
                    }

                    Iterator var17 = transferVO.getWorkItemIds().iterator();

                    while(var17.hasNext()) {
                        String workItemId = (String)var17.next();

                        try {
                            WorkItemModel workItem = this.getWorkflowInstanceFacade().getWorkItem(workItemId);
                            Boolean forwardResult = this.forwardWordItemWithNoMessage(transferVO.getUserId(), workItemId, transferVO.getTransferUserId(), transferVO.getTransferDeptId(), comment);
                            if (forwardResult) {
                                transferResult.setSuccess(transferResult.getSuccess() + 1);
                                if (workItem != null) {
                                    this.writeOperationLog(workItem.getInstanceId(), workItem.getId(), workItem.getActivityCode(), OperationType.WORK_ITEM_HANDOVER, transferVO);
                                }
                            } else {
                                transferResult.setFails(transferResult.getFails() + 1);
                                WorkItemModel itemModel = this.getWorkflowInstanceFacade().getWorkItem(workItemId);
                                WorkItemVO workItemVO = new WorkItemVO((WorkItemModel)null);
                                if (itemModel != null) {
                                    BeanUtils.copyProperties(itemModel, workItemVO);
                                } else {
                                    workItemVO.setId(workItemId);
                                }

                                workItems.add(workItemVO);
                            }
                        } catch (Exception var16) {
                            log.error("userId = {}, id = {}, transferUserId = {}", new Object[]{transferVO.getUserId(), workItemId, transferVO.getTransferUserId()});
                            log.error("交接部分工作时异常，e = {}", var16);
                            transferResult.setFails(transferResult.getFails() + 1);
                            WorkItemModel itemModel = this.getWorkflowInstanceFacade().getWorkItem(workItemId);
                            WorkItemVO workItemVO = new WorkItemVO((WorkItemModel)null);
                            if (itemModel != null) {
                                BeanUtils.copyProperties(itemModel, workItemVO);
                            } else {
                                workItemVO.setId(workItemId);
                            }

                            workItems.add(workItemVO);
                        }
                    }
                }

                transferResult.setWorkItems(workItems);
                this.sendDingMessage(transferVO, transferResult);
                return this.getOkResponseResult(transferResult, "工作交接已选任务或全部任务");
            }
          }
    }


    private void checkUser(String userId) {
        this.validateNotEmpty(userId, ErrCode.ORG_USER_ID_EMPTY.getErrMsg());
        UserModel userModel = this.getOrganizationFacade().getUser(userId);
        if (userModel == null) {
            throw new PortalException(ErrCode.ORG_USER_NONEXISTENT);
        }
    }

    private void transferBussiness(TransferVO transferVO, TransferResultVO resultVO) {
        if (transferVO.getTransferAll() != null && transferVO.getTransferAll()) {
            String schemaCode = transferVO.getSchemaCode();
            if (StringUtils.isBlank(schemaCode)) {
                List<BizSchemaModel> bizSchemaModels = this.getAppManagementFacade().getAllPublishBizSchema();
                if (CollectionUtils.isNotEmpty(bizSchemaModels)) {
                    bizSchemaModels.forEach((bizSchemaModel) -> {
                        transferVO.setSchemaCode(bizSchemaModel.getCode());
                        log.info("正在交接模型：{}", bizSchemaModel.getCode());
                        com.authine.cloudpivot.engine.component.query.api.Page<BizObjectModel> bizObjectModelPage = this.getBizObjectFacade().queryBizObjectItemDatas(transferVO.getUserId(), bizSchemaModel.getCode(), "", 0, 2147483647);
                        this.transferByPage(bizObjectModelPage, transferVO, resultVO);
                    });
                }
            } else {
                com.authine.cloudpivot.engine.component.query.api.Page<BizObjectModel> workItemsPage = this.getBizObjectFacade().queryBizObjectItemDatas(transferVO.getUserId(), schemaCode, transferVO.getSequenceStatus(), 0, 2147483647);
                this.transferByPage(workItemsPage, transferVO, resultVO);
            }
        } else {
            List<String> workItemIds = transferVO.getWorkItemIds();
            Iterator var4 = workItemIds.iterator();

            while(var4.hasNext()) {
                String id = (String)var4.next();

                try {
                    Boolean forwardResult = this.transferBussinessItem(transferVO, id);
                    if (forwardResult) {
                        resultVO.setSuccess(resultVO.getSuccess() + 1);
                    } else {
                        resultVO.setFails(resultVO.getFails() + 1);
                    }
                } catch (Exception var7) {
                    log.error("userId = {}, id = {}, transferUserId = {}", new Object[]{transferVO.getUserId(), id, transferVO.getTransferUserId()});
                    log.error("交接部分业务数据时异常，e = {}", var7);
                    resultVO.setFails(resultVO.getFails() + 1);
                }
            }
        }

    }


    private Boolean transferBussinessItem(TransferVO transferVO, String bizId) {
        Boolean isSuccess = false;

        try {
            BizObjectCreatedModel bizObjectCreatedModel = this.getBizObjectFacade().getBizObject(transferVO.getOriginator(), transferVO.getSchemaCode(), bizId);
            if (bizObjectCreatedModel != null && bizObjectCreatedModel.getData() != null && bizObjectCreatedModel.getData().size() > 0) {
                bizObjectCreatedModel.setOwner(transferVO.getTransferUserId());
                bizObjectCreatedModel.setOwnerDeptId(transferVO.getTransferDeptId());
                Boolean syncInstance = transferVO.getIsSyncInstance();
                syncInstance = syncInstance == null ? false : syncInstance;
                String newId = this.getBizObjectFacade().saveBizObject(transferVO.getOriginator(), bizObjectCreatedModel, syncInstance);
                if (StringUtils.isNotBlank(newId)) {
                    isSuccess = true;
                }

                if (StringUtils.isNotEmpty(bizObjectCreatedModel.getWorkflowInstanceId())) {
                    this.writeOperationLog(bizObjectCreatedModel.getWorkflowInstanceId(), bizId, (String)null, OperationType.DATA_HANDOVER, transferVO);
                }
            }
        } catch (Exception var7) {
            log.error("业务转办数据:{},异常-{}", bizId, var7);
        }

        return isSuccess;
    }


    protected void writeOperationLog(String instanceId, String workItemId, String activityCode, OperationType operationType, TransferVO transferVO) {
        String logger = "";
        String name;
        if (transferVO != null) {
            String id = transferVO.getUserId();
            name = null;
            if (StringUtils.isNotEmpty(id)) {
                name = this.getOrganizationFacade().getUser(id).getName();
            }

            String transferName = null;
            String transferUserId = transferVO.getTransferUserId();
            if (StringUtils.isNotEmpty(transferUserId)) {
                transferName = this.getOrganizationFacade().getUser(transferUserId).getName();
            }

            if (operationType.equals(OperationType.DATA_HANDOVER)) {
                if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(transferUserId) && StringUtils.isNotEmpty(transferName)) {
                    logger = "从" + name + "[" + id + "](是流程数据)交接给" + transferName + "[" + transferUserId + "]";
                }
            } else if (operationType.equals(OperationType.WORK_ITEM_HANDOVER) && StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(transferUserId) && StringUtils.isNotEmpty(transferName)) {
                logger = "从" + name + "[" + id + "]交接给" + transferName + "[" + transferUserId + "]";
            }
        } else {
            WorkflowInstanceModel workflowInstanceModel;
            if (operationType == OperationType.DELETE_INSTANCE) {
                workflowInstanceModel = this.getWorkflowInstanceFacade().getWorkflowInstance(instanceId);
                if (workflowInstanceModel != null) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("instanceId", instanceId);
                    jsonObject.put("instanceName", workflowInstanceModel.getInstanceName());
                    logger = jsonObject.toJSONString();
                }
            } else if (operationType == OperationType.TEMPORARY_STORAGE) {
                workflowInstanceModel = this.getWorkflowInstanceFacade().getWorkflowInstance(instanceId);
                if (workflowInstanceModel != null) {
                    name = workflowInstanceModel.getBizObjectId();
                }
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("备注：logger={}", JSONObject.toJSONString(logger));
            log.debug("备注：operationType={}", JSONObject.toJSONString(operationType.toString()));
        }

        this.writeBizObjectLog(instanceId, workItemId, activityCode, operationType, logger);
    }

    private void writeBizObjectLog(String instanceId, String workItemId, String activityCode, OperationType operationType, String logger) {
        try {
            String client = ClientUtils.getClient(this.request);
            String clientIP = ClientUtils.getClientIP(this.request);
            String userId = this.getUserId();
            this.logExecutorService.submit(() -> {
                this.getWorkflowInstanceFacade().writeBizObjectLog(userId, instanceId, workItemId, activityCode, operationType, client, clientIP, logger);
            });
        } catch (Exception var10) {
            log.error("write log error.", var10);
        }

    }

    private void sendDingMessage(TransferVO transferVO, TransferResultVO transferResult) {
        UserModel transUserModel = this.getOrganizationFacade().getUser(transferVO.getTransferUserId());
        if (transUserModel != null && !StringUtils.isBlank(transUserModel.getUserId())) {
            String title = "工作交接提醒!";
            UserModel userModel = this.getOrganizationFacade().getUser(transferVO.getUserId());
            String sysContent = "你于" + DateUtil.format(transferVO.getBeginTime(), DatePattern.NORM_DATETIME_FORMAT) + "发起的【" + userModel.getName() + "】工作交接已完成！成功" + transferResult.getSuccess() + "条,失败" + transferResult.getFails() + "条";
            sysContent = title + "\n\n" + sysContent;
            UserModel oprator = this.getOrganizationFacade().getUser(transferVO.getOriginator());
            if (null != oprator && !StringUtils.isEmpty(oprator.getUserId())) {
                try {
                    if (transferResult.getSuccess() > 0) {
                        String content = "管理员将" + userModel.getName() + "的" + transferResult.getSuccess() + "条" + (transferVO.getIsBusiness() ? "数据" : "待办任务") + "交接给了你,请尽快处理!";
                        content = title + "\n\n" + content;
                        MessageModel model = this.getMessageModel(title, content, transUserModel.getUserId(), transUserModel.getCorpId());
                        imMessageFacade.sendMessage(model);
                    }

                    if (StringUtils.isNotEmpty(oprator.getSourceId()) && !"admin".equals(oprator.getUsername())) {
                        MessageModel sysMessageModel = this.getMessageModel(title, sysContent, oprator.getUserId(), oprator.getCorpId());
                        if (transferResult.getSuccess() <= 0 && transferResult.getFails() <= 0) {
                            sysMessageModel.setContent("你于" + DateUtil.format(transferVO.getBeginTime(), DatePattern.NORM_DATETIME_FORMAT) + "发起的【" + userModel.getName() + "】工作交接失败！当前用户没有数据可交接");
                        }
                        imMessageFacade.sendMessage(sysMessageModel);
                    }
                } catch (Exception var10) {
                    log.error("工作交接发送钉钉消息失败：{}", var10);
                }

            }
        } else {
            log.info("钉钉发送失败：当前用户/userId {} 不存在", transferVO.getTransferUserId());
        }
    }

    private MessageModel getMessageModel(String title, String content, String userId, String corpId) {
        MessageModel model = new MessageModel();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        model.setTitle(title);
        model.setContent(content);
        model.setId(id);
        model.setReceivers(userId);
        model.setUrl("?messageId=" + id);
        model.setFailRetry(Boolean.TRUE);
        model.setFailUserRetry(Boolean.TRUE);
        model.setChannel(IMMessageChannelType.DINGTALK);
        model.setMessageType(IMMessageType.BUSINESS_REMIND);
        Map<String, Object> params = Maps.newHashMap();
        params.put("corpId", corpId);
        return model;
    }


    protected Boolean forwardWordItemWithNoMessage(String userId, String workItemId, String participantor, String transferDeptId, String comment) {
        if (log.isDebugEnabled()) {
            log.debug("转发任务...");
        }

        return this.getWorkflowInstanceFacade().forwardWordItemWithNoMessage(userId, workItemId, participantor, transferDeptId, comment);
    }


    private void transferByPage(com.authine.cloudpivot.engine.component.query.api.Page<BizObjectModel> bizObjectModelPage, TransferVO transferVO, TransferResultVO resultVO) {
        if (bizObjectModelPage != null && CollectionUtils.isNotEmpty(bizObjectModelPage.getContent())) {
            List<? extends BizObjectModel> content = bizObjectModelPage.getContent();
            Iterator var5 = content.iterator();

            while(var5.hasNext()) {
                BizObjectModel bizObjectModel = (BizObjectModel)var5.next();
                Map<String, Object> data = bizObjectModel.getData();
                String bizId = (String)data.get(DefaultPropertyType.ID.getCode());
                Boolean forwardResult = false;
                if (StringUtils.isNotBlank(bizId)) {
                    forwardResult = this.transferBussinessItem(transferVO, bizId);
                }

                if (forwardResult) {
                    resultVO.setSuccess(resultVO.getSuccess() + 1);
                } else {
                    resultVO.setFails(resultVO.getFails() + 1);
                }
            }
        }

    }


    protected Pageable getPageable(Integer page, Integer size, Sort.Direction direction, String... params) {
        Sort sort = new Sort(direction, params);
        return PageRequest.of(page == null ? 0 : page, size == null ? 10 : size, sort);
    }





    /**
     * @Description : 查询当前项目经理存在多少待办数据
     * @param ： userId
     * @param ： workflowCode
     * @param ： originator
     * @param ： page
     * @param ： size
     * @author : Liun
     * @date : 2020/7/14
     */
    public List<WorkItemModel>  listUserWorkItems(String userId,String workflowCode,String originator, Integer page, Integer size) {
        if (log.isDebugEnabled()) {
            log.debug("查询选定用户的待办列表：userId = {}, workflowCode = {}, originator = {}, page = {}, size = {}", userId, workflowCode, originator, page, size);
        }

        PageableSupport pageable = new PageableSupport(page, size, null);
        WorkItemQuerySpec workItemQuerySpec = new WorkItemQuerySpec();
        workItemQuerySpec.setUserId(userId);
        workItemQuerySpec.setUnitType(UnitType.USER);
        workItemQuerySpec.setWorkflowCode(workflowCode);
        workItemQuerySpec.setWorkflowName(StringUtils.EMPTY);
        workItemQuerySpec.setOriginator(originator);

        Page<WorkItemModel> workItemsPage = getWorkflowInstanceFacade().queryWorkItems(workItemQuerySpec, pageable);
        List<WorkItemModel> workItemModels = workItemsPage.getContent();
        Set<String> originatorDeptIds = workItemModels.stream().map(WorkItemModel::getDepartmentId).collect(Collectors.toSet());
        Map<String, List<DepartmentModel>> parentDepts = getOrganizationFacade().getDepartmentsByParentIds(Lists.newArrayList(originatorDeptIds));

        List<WorkItemVO> workItems = workItemModels.stream().filter(Objects::nonNull).map(workItemModel -> {
            if (MapUtils.isNotEmpty(parentDepts)) {
                workItemModel.setDepartmentName(getFullDepartmentName(parentDepts, workItemModel.getDepartmentId(), workItemModel.getDepartmentName()));
            }

            WorkItemVO workItemVO = new WorkItemVO(workItemModel);
            BeanUtils.copyProperties(workItemModel, workItemVO);
            WorkflowTemplateHeaderModel header = getAppManagementFacade().getWorkflowTemplateHeader(workItemModel.getWorkflowCode());
            workItemVO.setWorkflowName(header == null ? StringUtils.EMPTY : header.getWorkflowName());
            workItemVO.setImgUrl(getUserImg(workItemModel.getOriginator()));
            return workItemVO;
        }).collect(Collectors.toList());
      return  workItemModels;
    }


    /**
     * 组织展示全路径
     *
     * @param parentDepts    父级部门集合
     * @param departmentId   部门id
     * @param departmentName 部门名称
     * @return 组织全路径
     */
    protected String getFullDepartmentName(Map<String, List<DepartmentModel>> parentDepts, String departmentId,
                                           String departmentName) {
        if (StringUtils.isEmpty(departmentId)) {
            return StringUtils.EMPTY;
        }
        List<String> deptNames = parentDepts.get(departmentId).stream().map(DepartmentModel::getName)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(deptNames)) {
            return StringUtils.EMPTY;
        }
        Collections.reverse(deptNames);
        if (deptNames.size() > 1) {
            deptNames.remove(0);
        }
        if (StringUtils.isEmpty(departmentName)) {
            return deptNames.stream().collect(Collectors.joining("/"));
        }
        return deptNames.stream().collect(Collectors.joining("/"));
    }


    /**
     * 获取用户头像
     *
     * @param originator 用户id
     * @return String
     */
    protected String getUserImg(String originator) {
        UserModel originatorInfo = getUser(originator);
        if (originatorInfo != null) {
            if (log.isDebugEnabled()) {
                log.debug("originatorInfo.getImgUrl = {}", originatorInfo.getImgUrl());
            }

            return originatorInfo.getImgUrl();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户id
     * @return UserModel
     */
    protected UserModel getUser(String userId) {
        return getOrganizationFacade().getUser(userId);
    }


}
